package com.yundingai.service.impl;

import com.yundingai.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author 谢辉
 * @Date 2025/7/24 18:28
 * @Description TODO
 **/
@Service
public class TokenServiceImpl implements TokenService {
    private static final String USER_TOKEN_KEY = "user:token:";
    private static final String TOKEN_USER_KEY = "token:user:";
    private static final long EXPIRATION_HOURS = 24;// Token过期时间(小时)

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    //保存用户Token到Redis
    @Override
    public void saveUserToken(Long userId, String token) {
        // 使旧Token失效
        String oldToken = (String) redisTemplate.opsForValue().get(USER_TOKEN_KEY + userId);
        if (oldToken != null) {
            redisTemplate.delete(TOKEN_USER_KEY + oldToken);
        }

        // 存储新Token，双向映射机制
        redisTemplate.opsForValue().set(
                USER_TOKEN_KEY + userId,
                token,
                EXPIRATION_HOURS, TimeUnit.HOURS
        );
        redisTemplate.opsForValue().set(
                TOKEN_USER_KEY + token,
                userId,
                EXPIRATION_HOURS, TimeUnit.HOURS
        );
    }

    //验证Token是否有效
    @Override
    public boolean validateToken(String token) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(TOKEN_USER_KEY + token));
    }

    //移除指定用户的Token
    @Override
    public void removeToken(Long userId) {
        // 1. 获取用户当前Token
        String token = (String) redisTemplate.opsForValue().get(USER_TOKEN_KEY + userId);
        if (token != null) {
            // 2. 删除双向映射
            redisTemplate.delete(TOKEN_USER_KEY + token);
            redisTemplate.delete(USER_TOKEN_KEY + userId);
        }
    }

}
